package com.tianhui.consignortwofei.api.hetong;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by huling on 2018/3/28.
 */

public class CusstomInterceptor implements Interceptor {

    private Context context;
    private static CusstomInterceptor interceptor;
    private final Charset UTF8 = Charset.forName("UTF-8");
    //下面这些api，当登录失效时并且isNeedToLoginPageAtResponse为false时不需要跳转到登录页面
    private String[] noInterceptApi = new String[]{
            "changcheng/cc/mine/get_info"
    };
    private String noInterceptApiSuffix = ".auth";
    private String needInterceptApi = "changcheng/cc";

    public CusstomInterceptor(Context context) {
        this.context = context;
    }

    public static CusstomInterceptor getInstance(Context context) {
        if (interceptor == null) {
            synchronized (CusstomInterceptor.class) {
                if (interceptor == null) {
                    interceptor = new CusstomInterceptor(context);
                }
            }
        }
        return interceptor;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
//        Request newRequest = request.newBuilder()
//                .addHeader("XX-Token", getToken() )
//                .addHeader( "XX-Device-Type" , "android" )
//                .build();
//        return chain.proceed( newRequest );
        Response response = chain.proceed(request);
        String url = request.url().toString();
        if (!TextUtils.isEmpty(needInterceptApi)
                && url.contains(needInterceptApi)
                && !url.contains(noInterceptApiSuffix)
//                && !isInInterceptApiArr( noInterceptApi , url )
                ) {
            handleResponse(response, url);
        }
        return response;
    }

    /**
     * 处于数组中的链接不需要拦截
     *
     * @param arr
     * @param url
     * @return
     */
    private boolean isInInterceptApiArr(String[] arr, String url) {
        if (arr == null || arr.length == 0) {
            return false;
        }
        for (String api : arr) {
            if (url.contains(api)) {
                return true;
            }
            continue;
        }
        return false;
    }

    /**
     * 获取响应数据
     *
     * @param response
     * @param responseBody
     * @throws IOException
     */
    private String getResponseBodyData(Response response, ResponseBody responseBody) throws IOException {
        String responseBodyStr = null;
        if (response != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    e.printStackTrace();
                }
            }
            responseBodyStr = buffer.clone().readString(charset);
        }
        return responseBodyStr;
    }

    /**
     * 处理响应数据
     *
     * @param response
     * @throws IOException
     */
    private void handleResponse(Response response, String url) throws IOException {
        String responseResult = getResponseBodyData(response, response.body());
        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(responseResult);
            if (jsonObject == null) {
                return;
            }
            int code = jsonObject.getInt("code");
            if (code == HttpConstants.RESPONSE_CODE_700
//                    || code == HttpConstants.RESPONSE_CODE_701
//                    || code == HttpConstants.RESPONSE_CODE_702
                    ) {
                Log.i( "TAG" , "============================是否执===============" );
//                toLoginPage();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当登陆已失效直接跳转到登陆页面
     * 造成原因: 可能是多个设备使用同一个账号x
     */
    private synchronized void toLoginPage() {
//        if (MyApplication.getInstance().isNeedToLoginPageAtResponse) {
//            MyApplication.getInstance().isNeedToLoginPageAtResponse = false;
//            RxBus.getInstance().post(RxBusBaseMessage.EventCode.TO_LOGIN_PAGE_TOKEN, new RxBusBaseMessage());
////            EventBus.getDefault().post(  new LoginEvent( LoginEvent.Constants.TO_LOGIN_PAGE_TOKEN , "Token已失效，请重新登录!" ));
//        }
    }
}
